﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

public partial class Admin_Assignments_Quiz : System.Web.UI.Page
{
    ILE_Global ileGlobal = new ILE_Global();
    ILE_Config ileConfig = new ILE_Config();

    protected string Mode
    {
        get
        {
            return (string)ViewState["Mode"];
        }
        set
        {
            ViewState["Mode"] = value;
        }
    }
    protected int CourseID
    {
        get
        {
            return (int)ViewState["CourseID"];
        }
        set
        {
            ViewState["CourseID"] = value;
        }
    }

    protected int SectionNumber
    {
        get
        {
            return (int)ViewState["SectionNumber"];
        }
        set
        {
            ViewState["SectionNumber"] = value;
        }
    }

    protected int StandardID
    {
        get
        {
            return (int)ViewState["StandardID"];
        }
        set
        {
            ViewState["StandardID"] = value;
        }
    }

    protected string strQuizAssignment
    {
        get
        {
            return Session["xDocQuizAssignment"].ToString();
        }
        set
        {
            Session["xDocQuizAssignment"] = value;
        }
        //get
        //{
        //    return (XDocument)Cache["xDocQuizAssignment" + User.Identity.Name.ToString()];
        //}
        //set
        //{
        //    Cache["xDocQuizAssignment" + User.Identity.Name.ToString()] = (XDocument)value;
        //}
    }

    StatisticsBLL statisticsLogic = new StatisticsBLL();

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            try
            {
                Mode = Request.QueryString["Mode"];
                CourseID = Convert.ToInt32(Request.QueryString["CourseID"]);
                SectionNumber = Convert.ToInt32(Request.QueryString["SectionNumber"]);
                StandardID = Convert.ToInt32(Request.QueryString["StandardID"]);
            }
            catch { }

            GridViewCourses.Sort("Title", SortDirection.Ascending);

            if (Mode == "Create")
            {
                WizardCreateQuizAssignment.NavigationStyle.CssClass = "Hidden";
                PanelCreateQuizAssignment.Visible = true;
            }
            else if (Mode == "Edit")
            {
                WizardEditQuizAssignment.NavigationStyle.CssClass = "Hidden";
                PanelEditQuizAssignment.Visible = true;
            }

            strQuizAssignment = String.Empty;
        }

        int UserID = 0;

        try
        {
            UserID = Convert.ToInt32(Session["UserID"]);
        }
        catch (NullReferenceException ex)
        {
            ileGlobal.RecordError("Assignments_Quiz.aspx.cs:Page_Load:001", ex, "User Session Ended Unexpectedly", 3, Request.Browser);
            FormsAuthentication.SignOut();
            // *SteveMsg
            string _msg = "Your Session Information has ended. You have been logged out to prevent errors.";
            ModalPopupMessage.ShowModalPopup_Redirect("ILE Message", _msg, 2, "../Default.aspx");
        }
    }

    protected void btnOpenCreateQuizAssignment_Click(object sender, EventArgs e)
    {
        ResetQuizAssignment("Create");
    }

    private void ResetQuizAssignment(string Mode)
    {
        if (Mode == "Create")
        {
            Response.Redirect("Assignments_Quiz.aspx?Mode=Create");
        }
        else if (Mode == "Edit")
        {
            Response.Redirect("Assignments_Quiz.aspx?Mode=Edit");
        }
    }

    protected void btnOpenEditQuizAssignment_Click(object sender, EventArgs e)
    {
        ResetQuizAssignment("Edit");
    }

    protected void GridViewCourses_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (GridViewCourses.SelectedIndex != -1)
        {
            CourseID = Convert.ToInt32(((GridView)sender).SelectedValue.ToString());
            LoadSectionsByCourseID(false);
            WizardCreateQuizAssignment.NavigationStyle.CssClass = "";
        }
        else
        {
            PanelCreateQuizSections.Visible = false;
            WizardCreateQuizAssignment.NavigationStyle.CssClass = "Hidden";
        }
    }

    protected void chkboxCreateQuizSectionsShowDisabled_CheckedChanged(object sender, EventArgs e)
    {
        LoadSectionsByCourseID(((CheckBox)sender).Checked);
    }

    protected void LoadSectionsByCourseID(bool showDisabled)
    {
        ClassBLL classLogic = new ClassBLL();

        lstboxSections.Items.Clear();

        Classes.Courses_SectionDataTable sections = classLogic.GetSectionsByCourseID(CourseID, false);

        foreach (Classes.Courses_SectionRow section in sections)
        {
            ListItem newItem = new ListItem(section.SectionNumber.ToString(), section.SectionNumber.ToString());
            if (showDisabled)
            {
                lstboxSections.Items.Add(newItem);
            }
            else
            {
                if (section.IsEnabled == true)
                    lstboxSections.Items.Add(newItem);
            }
        }

        PanelCreateQuizSections.Visible = true;
    }

    protected void WizardCreateQuizAssignment_ActiveStepChanged(object sender, EventArgs e)
    {
        if (WizardCreateQuizAssignment.ActiveStepIndex == 0)
        {
            strQuizAssignment = String.Empty;
            // Hide Selected Sections when User comes back to this step
            lblCreateQuizSelectedSections.Text = "Selected Sections: ";
            lblCreateQuizSelectedSections.Visible = false;
        }
        else if (WizardCreateQuizAssignment.ActiveStepIndex == 1)
        {
            StandardID = Convert.ToInt32(RadioButtonListStandardID.SelectedValue);

            ClassStandardsBLL classStandardsLogic = new ClassStandardsBLL();
            try
            {
                if (classStandardsLogic.GetClassStandard(CourseID, StandardID).IsStandardEnabled == false)
                {
                    // *SteveMsg
                    string _msg = "The standard you have selected has been disabled for the course.<br />You are assigning the quiz for this section only.<br />Be sure to verify that the standard has been enabled for this section.";
                    ModalPopupMessage.ShowModalPopup("ILE Message", _msg, 2);
                }
            }
            catch
            {
                // *SteveMsg
                string _msg = "The standard you have selected has been disabled for the course.<br />You are assigning the quiz for this section only.<br />Be sure to verify that the standard has been enabled for this section.";
                ModalPopupMessage.ShowModalPopup("ILE Message", _msg, 2);
            }

            if (GridViewCourses.SelectedIndex == -1)
            {
                WizardCreateQuizAssignment.ActiveStepIndex = 0;
                // *SteveMsg
                string _msg = "You must select a class to assign the quiz to.";
                ModalPopupMessage.ShowModalPopup("ILE Message", _msg, 2);
                return;
            }

            if (lstboxSections.SelectedIndex == -1)
            {
                WizardCreateQuizAssignment.ActiveStepIndex = 0;
                // *SteveMsg
                string _msg = "At least 1 section must be selected from the 'Sections' Listbox.";
                ModalPopupMessage.ShowModalPopup("ILE Message", _msg, 2);
            }
            else
            {
                ddlistModelSection.Items.Clear();
                foreach (ListItem item in lstboxSections.Items)
                {
                    if (item.Selected)
                    {
                        ListItem newItem = new ListItem(item.Text, item.Value);
                        ddlistModelSection.Items.Add(newItem);
                    }
                }

                ddlistModelSection.SelectedIndex = 0;

                lblModelSection.Text = ddlistModelSection.Items[0].Value;

                // Showing Selected Sections
                {
                    foreach (ListItem item in lstboxSections.Items)
                    {
                        if (item.Selected)
                            lblCreateQuizSelectedSections.Text += item.Value.ToString() + ", ";
                    }

                    lblCreateQuizSelectedSections.Text = lblCreateQuizSelectedSections.Text.Substring(0, lblCreateQuizSelectedSections.Text.Length - 2);
                    lblCreateQuizSelectedSections.Visible = true;
                }

                LoadRelatedQuizSets();
            }
        }
        else if (WizardCreateQuizAssignment.ActiveStepIndex == 2)
        {
            ClassStandardsBLL classStandardsLogic = new ClassStandardsBLL();

            XDocument xDocQuizAssignment = new XDocument();
            if (strQuizAssignment != String.Empty)
                xDocQuizAssignment = XDocument.Parse(strQuizAssignment);

            ClassStandards.Courses_Standard_SectionRow section = classStandardsLogic.GetClassSectionStandard(CourseID, SectionNumber, StandardID);
            if (section == null || section.UseSectionInfo == false)
            {
                // If null, it means this Section is using the Class Default Settings.
                ClassStandards.Courses_LearnObjDataTable learnObjs = classStandardsLogic.GetClassLearnObjs(CourseID, StandardID);

                if (learnObjs.Count <= 0)
                {
                    // *SteveMsg
                    string _msg = "There are no quiz sets available. Please select a section that has at least one learning object added.";
                    ModalPopupMessage.ShowModalPopup("ILE Message", _msg, 2);
                    WizardCreateQuizAssignment.ActiveStepIndex = 1;
                }
                else
                {
                    if (strQuizAssignment == String.Empty)
                    {
                        xDocQuizAssignment.Declaration = new XDeclaration("1.0", "utf-8", "yes");

                        //UsersBLL usersLogic = new UsersBLL();
                        //int UserID = usersLogic.GetUserByUsername(HttpContext.Current.User.Identity.Name.ToString()).UserID;
                        int UserID = Convert.ToInt32(Session["UserID"].ToString());

                        xDocQuizAssignment.Document.Add(new XElement("quizassignment",
                                                new XAttribute("name", String.Empty),
                                                new XAttribute("assignedby", UserID.ToString()),
                                                    new XElement("questions")));


                        ddlistQuestionFilterByQuizSet.Items.Clear();
                        ddlistQuestionFilterByQuizSet.Items.Add(new ListItem("Show All", "0"));

                        foreach (ClassStandards.Courses_LearnObjRow learnObj in learnObjs)
                        {
                            if (learnObj.IsEnabled)
                            {
                                LearnObjsBLL learnObjLogic = new LearnObjsBLL();
                                LearnObjs.LearnObjsRow tempLearnObj = learnObjLogic.GetLearnObj(learnObj.LearnObjID);
                                ddlistQuestionFilterByQuizSet.Items.Add(new ListItem("Quiz for " + tempLearnObj.Title, tempLearnObj.LearnObjID.ToString()));

                                XDocument quizSet = XDocument.Parse(tempLearnObj.LearnObjQuizQuestions);

                                List<XElement> _questions = quizSet.Descendants("question").ToList();

                                foreach (XElement question in _questions)
                                {
                                    try
                                    {
                                        question.Add(new XAttribute("learnobjid", learnObj.LearnObjID.ToString()));
                                    }
                                    catch
                                    {
                                    }
                                    try
                                    {
                                        question.Add(new XAttribute("excluded", "false"));
                                    }
                                    catch
                                    {
                                    }
                                    xDocQuizAssignment.Element("quizassignment").Element("questions").Add(question);
                                }
                            }
                        }
                    }

                    strQuizAssignment = xDocQuizAssignment.ToString();

                    XDocument xDocQuizAssignmentFiltered = new XDocument(xDocQuizAssignment);

                    try
                    {
                        xDocQuizAssignmentFiltered.Descendants("question").Where(
                            el => (string)el.Attribute("learnobjid").Value == "0").Remove();
                    }
                    catch
                    {
                    }

                    XmlDataSourceQuestions.EnableCaching = false;
                    XmlDataSourceQuestions.Data = xDocQuizAssignmentFiltered.ToString();
                    XmlDataSourceQuestions.DataBind();

                    RepeaterQuestions.DataBind();

                    RepeaterQuestions.Visible = true;
                }
            }
            else
            {
                //Must load it by section
                ClassStandards.Courses_LearnObj_SectionDataTable learnObjs = classStandardsLogic.GetClassSectionLearnObjs(CourseID, SectionNumber, StandardID);
                if (learnObjs.Count <= 0)
                {
                    // *SteveMsg
                    string _msg = "There are no quiz sets available. Please select a section that has at least one learning object added.";
                    ModalPopupMessage.ShowModalPopup("ILE Message", _msg, 2);
                    WizardCreateQuizAssignment.ActiveStepIndex = 1;
                }
                else
                {
                    if (strQuizAssignment == String.Empty)
                    {
                        xDocQuizAssignment.Declaration = new XDeclaration("1.0", "utf-8", "yes");


                        //UsersBLL usersLogic = new UsersBLL();
                        //int UserID = usersLogic.GetUserByUsername(HttpContext.Current.User.Identity.Name.ToString()).UserID;
                        int UserID = Convert.ToInt32(Session["UserID"].ToString());
                        xDocQuizAssignment.Document.Add(new XElement("quizassignment",
                                                new XAttribute("name", String.Empty),
                                                new XAttribute("assignedby", UserID.ToString()),
                                                    new XElement("questions")));


                        ddlistQuestionFilterByQuizSet.Items.Clear();
                        ddlistQuestionFilterByQuizSet.Items.Add(new ListItem("Show All", "0"));

                        foreach (ClassStandards.Courses_LearnObj_SectionRow learnObj in learnObjs)
                        {
                            if (learnObj.IsEnabled)
                            {
                                LearnObjsBLL learnObjsLogic = new LearnObjsBLL();
                                LearnObjs.LearnObjsRow tempLearnObj = learnObjsLogic.GetLearnObj(learnObj.LearnObjID);
                                ddlistQuestionFilterByQuizSet.Items.Add(new ListItem("Quiz for " + tempLearnObj.Title, tempLearnObj.LearnObjID.ToString()));

                                XDocument quizSet = XDocument.Parse(tempLearnObj.LearnObjQuizQuestions);

                                List<XElement> _questions = quizSet.Descendants("question").ToList();

                                foreach (XElement question in _questions)
                                {
                                    try
                                    {
                                        question.Add(new XAttribute("learnobjid", learnObj.LearnObjID.ToString()), new XAttribute("excluded", "false"));
                                    }
                                    catch (InvalidOperationException ex)
                                    {
                                        // do nothing
                                    }
                                    xDocQuizAssignment.Document.Element("quizassignment").Element("questions").Add(question);
                                }
                            }
                        }
                    }

                    strQuizAssignment = xDocQuizAssignment.ToString();

                    XDocument xDocQuizAssignmentFiltered = new XDocument(xDocQuizAssignment);

                    xDocQuizAssignmentFiltered.Descendants("question").Where(
                        el => (string)el.Attribute("learnobjid").Value == "0").Remove();

                    XmlDataSourceQuestions.EnableCaching = false;
                    XmlDataSourceQuestions.Data = xDocQuizAssignmentFiltered.ToString();
                    XmlDataSourceQuestions.DataBind();

                    RepeaterQuestions.DataBind();

                    RepeaterQuestions.Visible = true;
                }
            }

            strQuizAssignment = xDocQuizAssignment.ToString();
        }
        else if (WizardCreateQuizAssignment.ActiveStepIndex == 3)
        {

        }
        else if (WizardCreateQuizAssignment.ActiveStepIndex == 4)
        {
            FillDdlistQuestionsOverviewFilterByQuizSet();
            LoadQuestionsOverview();
        }
        else if (WizardCreateQuizAssignment.ActiveStepIndex == 5)
        {
            ClassBLL classLogic = new ClassBLL();
            Classes.CoursesRow course = classLogic.GetCourse(CourseID);
            string Standard = String.Empty;
            switch (StandardID)
            {
                case 1:
                    Standard = "Getting Started";
                    break;
                case 2:
                    Standard = "Finding Sources";
                    break;
                case 3:
                    Standard = "Evaluating Sources";
                    break;
                case 4:
                    Standard = "Writing with Sources";
                    break;
            }
            txtGeneralQuizAssignmentName.Text = Standard + " Quiz For " + course.Title;
            FillDdlistNumberOfQuestionsToGenerate();
            txtGeneralStartDate.Text = DateTime.Now.ToString("MM/dd/yyyy");
            txtGeneralEndDate.Text = DateTime.Now.AddDays(1).ToString("MM/dd/yyyy");
        }
    }

    protected void WizardCreateQuizAssignment_NextButtonClick(object sender, WizardNavigationEventArgs e)
    {
        if (e.NextStepIndex == 3)
        {
            WizardCreateQuizAssignment.ActiveStepIndex = 5;
        }
    }

    protected void lnkModelSectionAdvanced_Click(object sender, EventArgs e)
    {
        PanelModelSectionDropDownList.Visible = true;
        lnkModelSectionAdvanced.Visible = false;
    }

    protected void ddlistModelSection_SelectedIndexChanged(object sender, EventArgs e)
    {
        strQuizAssignment = String.Empty;
        LoadRelatedQuizSets();
    }

    private void LoadRelatedQuizSets()
    {
        ClassStandardsBLL classStandardsLogic = new ClassStandardsBLL();

        SectionNumber = Convert.ToInt32(ddlistModelSection.SelectedValue);

        lblModelSection.Text = SectionNumber.ToString();

        ClassStandards.Courses_Standard_SectionRow section = classStandardsLogic.GetClassSectionStandard(CourseID, SectionNumber, StandardID);
        if (section == null || section.UseSectionInfo == false)
        {
            // If null, it means this Section is using the Class Default Settings.
            lblCreateQuizUseClassDefault.Text = "<li style='font-weight: bold;'>Section " + SectionNumber.ToString() + " is using the Course Default Setting.</li>";
            ClassStandards.Courses_LearnObjDataTable learnObjs = classStandardsLogic.GetClassLearnObjs(CourseID, StandardID);

            lblCreateQuizAvailableQuizSets.Text = "<li style='font-weight: bold;'>Quiz questions will be drawn from the following learning objects<ul style='font-weight: normal;'>";

            if (learnObjs.Count <= 0)
            {
                lblCreateQuizAvailableQuizSets.Text += "<li>No Learning Objects have been added. Go to the Manage Class Std. page to add Learning Objects to the course.</li>";
            }
            else
            {
                foreach (ClassStandards.Courses_LearnObjRow learnObj in learnObjs)
                {
                    LearnObjsBLL learnObjsLogic = new LearnObjsBLL();
                    LearnObjs.LearnObjsRow tempLearnObj = learnObjsLogic.GetLearnObj(learnObj.LearnObjID);
                    if (learnObj.IsEnabled)
                    {
                        lblCreateQuizAvailableQuizSets.Text += "<li>" + "Quiz for " + tempLearnObj.Title + "</li>";
                    }
                    else
                    {
                        lblCreateQuizAvailableQuizSets.Text += "<li style='Color: Gray; font-style: italic;'>" + "Quiz for " + tempLearnObj.Title + " - Disabled</li>";
                    }
                }
            }

            lblCreateQuizAvailableQuizSets.Text += "</ul></li>";

            lblCreateQuizConflict.Text = String.Empty;

            // Check Conflict with other sections
            lblCreateQuizConflict.Visible = false;
            foreach (ListItem item in ddlistModelSection.Items)
            {
                int tempSectionNumber = Convert.ToInt32(item.Value);
                if (!item.Selected)
                {
                    ClassStandards.Courses_Standard_SectionRow tempSection = classStandardsLogic.GetClassSectionStandard(CourseID, tempSectionNumber, StandardID);
                    if (tempSection != null && tempSection.UseSectionInfo == true)
                    {
                        ClassStandards.Courses_LearnObj_SectionDataTable sectionLearnObjs = classStandardsLogic.GetSectionLearnObjs(CourseID, tempSectionNumber, StandardID);
                        foreach (ClassStandards.Courses_LearnObj_SectionRow sectionLearnObj in sectionLearnObjs)
                        {
                            if (learnObjs.FindByCourseIDStandardIDLearnObjID(CourseID, StandardID, sectionLearnObj.LearnObjID) == null)
                            {
                                // *SteveMsg
                                lblCreateQuizConflict.Text += "<li style='color: Red;'>Section " + tempSectionNumber.ToString() + " has a Learning Object that Section " + SectionNumber.ToString() + " does not have.</li>";
                                lblCreateQuizConflict.Visible = true;
                                return;
                            }
                        }
                    }
                }
            }
        }
        else
        {
            // *SteveMsg
            lblCreateQuizUseClassDefault.Text = "<li style='font-weight: bold;'>Section " + SectionNumber.ToString() + " is using its own Standard Settings.</li>";

            lblCreateQuizAvailableQuizSets.Text = "<li style='font-weight: bold;'>Learning Objects related Quiz Sets<ul style='font-weight: normal;'>";

            ClassStandards.Courses_LearnObj_SectionDataTable sectionLearnObjs = classStandardsLogic.GetSectionLearnObjs(CourseID, SectionNumber, StandardID);
            if (sectionLearnObjs.Count <= 0)
            {
                lblCreateQuizAvailableQuizSets.Text += "<li>No Learning Object has been added. Please go to Manage Class Std. page to add Learning Objects to the section.</li>";
            }
            else
            {
                foreach (ClassStandards.Courses_LearnObj_SectionRow learnObj in sectionLearnObjs)
                {
                    LearnObjsBLL learnObjsLogic = new LearnObjsBLL();
                    LearnObjs.LearnObjsRow tempLearnObj = learnObjsLogic.GetLearnObj(learnObj.LearnObjID);
                    if (learnObj.IsEnabled)
                    {
                        lblCreateQuizAvailableQuizSets.Text += "<li>" + "Quiz for " + tempLearnObj.Title + "</li>";
                    }
                    else
                    {
                        lblCreateQuizAvailableQuizSets.Text += "<li style='Color: Gray; font-style: italic;'>" + "Quiz for " + tempLearnObj.Title + " - Disabled</li>";
                    }
                }
            }

            lblCreateQuizAvailableQuizSets.Text += "</ul></li>";

            //Check Conflict
            lblCreateQuizConflict.Visible = false;
            bool flag = false;
            ClassStandards.Courses_LearnObjDataTable learnObjs = classStandardsLogic.GetClassLearnObjs(CourseID, StandardID);

            foreach (ClassStandards.Courses_LearnObj_SectionRow sectionLearnObj in sectionLearnObjs)
            {
                if (learnObjs.FindByCourseIDStandardIDLearnObjID(CourseID, StandardID, sectionLearnObj.LearnObjID) == null)
                {
                    flag = true;
                    break;
                }
            }

            foreach (ListItem item in ddlistModelSection.Items)
            {
                int tempSectionNumber = Convert.ToInt32(item.Value);
                if (!item.Selected)
                {
                    ClassStandards.Courses_Standard_SectionRow tempSection = classStandardsLogic.GetClassSectionStandard(CourseID, tempSectionNumber, StandardID);
                    if (tempSection != null && tempSection.UseSectionInfo == true)
                    {
                        sectionLearnObjs = classStandardsLogic.GetSectionLearnObjs(CourseID, tempSectionNumber, StandardID);
                        foreach (ClassStandards.Courses_LearnObj_SectionRow sectionLearnObj in sectionLearnObjs)
                        {
                            if (learnObjs.FindByCourseIDStandardIDLearnObjID(CourseID, StandardID, sectionLearnObj.LearnObjID) == null)
                            {
                                // *SteveMsg
                                lblCreateQuizConflict.Text = "<li style='color: Red;'>Section " + tempSectionNumber.ToString() + " has a Learning Object that Section " + SectionNumber.ToString() + " does not have.</li>";
                                return;
                            }
                        }
                    }
                    else
                    {
                        if (flag)
                        {
                            lblCreateQuizConflict.Text = "<li style='color: Red;'>Section " + SectionNumber.ToString() + " has Learning Objects(s) that are not included in the Course Default for this standard.</li>";
                            lblCreateQuizConflict.Visible = true;
                            break;
                        }
                    }
                }

                //// Display Warning if the section is already assigned with a Quiz...
                //AssignmentsBLL assignmentsLogic = new AssignmentsBLL();
                //int numberOfAssignedQuiz = assignmentsLogic.IsRelationDuplicated(CourseID, tempSectionNumber, StandardID);
                //if (numberOfAssignedQuiz >= 1)
                //{
                //    // *SteveMsg
                //    lblCreateQuizConflict.Text += "<li style='color: #FF850B;'>Just a friendly warning, there is a quiz assignment assigned to Section " + tempSectionNumber.ToString() + " already.";
                //    lblCreateQuizConflict.Visible = true;
                //}
            }


        }
    }

    protected void RepeaterQuestions_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {

    }

    protected void btnCreateQuizJumpToAddCustomQuestions_Click(object sender, EventArgs e)
    {
        WizardCreateQuizAssignment.ActiveStepIndex = 3;
    }

    protected int GetQuestionStats(int LearnObjID, int QuestionID, bool IsAnsweredCorrectly)
    {
        int result = statisticsLogic.CountByLearnObjIdAndQuestionId(LearnObjID, QuestionID, IsAnsweredCorrectly);

        if (IsAnsweredCorrectly == false && result == 0)
        {
            return 0;
        }
        else
        {
            return result;
        }
    }

    protected double GetQuestionStatsPercentage(int LearnObjID, int QuestionID)
    {
        int correct = statisticsLogic.CountByLearnObjIdAndQuestionId(LearnObjID, QuestionID, true);
        int incorrect = statisticsLogic.CountByLearnObjIdAndQuestionId(LearnObjID, QuestionID, false);

        if ((incorrect + correct) == 0)
        {
            return 0;
        }
        else
        {
            return (double)correct / ((double)incorrect + correct);
        }
    }



    protected void ddlistQuestionFilterByQuizSet_SelectedIndexChanged(object sender, EventArgs e)
    {
        // FILTER
        switch (((DropDownList)sender).SelectedIndex)
        {
            case 0:
                //XmlDataSourceQuestions.EnableCaching = false;
                XmlDataSourceQuestions.Data = strQuizAssignment;
                XmlDataSourceQuestions.DataBind();
                RepeaterQuestions.DataBind();
                break;
            default:
                int LearnObjID = Convert.ToInt32(((DropDownList)sender).SelectedValue);
                XDocument xDocQuizAssignmentFiltered = XDocument.Parse(strQuizAssignment);

                //var query = from c in xDocQuizAssignmentFiltered.Descendants("question")
                //            where (string)c.Attribute("learnobjid").Value != LearnObjID.ToString()
                //            select c;

                List<XElement> _questions = xDocQuizAssignmentFiltered.Descendants("question").Where(
                    el => (int)el.Attribute("learnobjid") != LearnObjID).ToList();

                foreach (XElement question in _questions)
                {
                    question.Remove();
                }

                XmlDataSourceQuestions.EnableCaching = false;
                XmlDataSourceQuestions.Data = xDocQuizAssignmentFiltered.ToString();
                XmlDataSourceQuestions.DataBind();
                RepeaterQuestions.DataBind();
                break;
        }
    }

    protected void chkboxRequired_CheckedChanged(object sender, EventArgs e)
    {
        CheckBox chkboxObj = (CheckBox)sender;
        string[] arguments = new string[2];
        arguments = chkboxObj.Text.Split(';');
        int LearnObjID = Convert.ToInt32(arguments[0]);
        int QuestionID = Convert.ToInt32(arguments[1]);

        XDocument xDocQuizAssignment = new XDocument();
        if (strQuizAssignment != String.Empty)
            xDocQuizAssignment = XDocument.Parse(strQuizAssignment);

        var query = from c in xDocQuizAssignment.Elements("quizassignment").Elements("questions").Elements("question")
                    where (string)c.Attribute("learnobjid").Value == LearnObjID.ToString() &&
                          (string)c.Attribute("id").Value == LearnObjID.ToString()
                    select c;

        XElement question = xDocQuizAssignment.Descendants("question").First(
                    el => (int)el.Attribute("learnobjid") == LearnObjID && (int)el.Attribute("id") == QuestionID);

        question.Attribute("defaultrequired").Value = chkboxObj.Checked ? "true" : "false";
        question.ReplaceAttributes(
            new XAttribute("learnobjid", LearnObjID.ToString()),
            new XAttribute("id", QuestionID.ToString()),
            new XAttribute("difficulty", question.Attribute("difficulty").Value),
            new XAttribute("point", question.Attribute("point").Value),
            new XAttribute("defaultrequired", chkboxObj.Checked ? "true" : "false"),
            new XAttribute("excluded", question.Attribute("excluded").Value));

        strQuizAssignment = xDocQuizAssignment.ToString();
    }

    protected void chkboxExcluded_CheckedChanged(object sender, EventArgs e)
    {
        CheckBox chkboxObj = (CheckBox)sender;
        string[] arguments = new string[2];
        arguments = chkboxObj.Text.Split(';');
        int LearnObjID = Convert.ToInt32(arguments[0]);
        int QuestionID = Convert.ToInt32(arguments[1]);

        XDocument xDocQuizAssignment = new XDocument();
        if (strQuizAssignment != String.Empty)
            xDocQuizAssignment = XDocument.Parse(strQuizAssignment);

        List<XElement> _question = xDocQuizAssignment.Descendants("question").Where(
                    el => (int)el.Attribute("id") == QuestionID && (int)el.Attribute("learnobjid") == LearnObjID).ToList();
        _question[0].ReplaceAttributes(
            new XAttribute("learnobjid", LearnObjID.ToString()),
            new XAttribute("id", QuestionID.ToString()),
            new XAttribute("difficulty", _question[0].Attribute("difficulty").Value),
            new XAttribute("point", _question[0].Attribute("point").Value),
            new XAttribute("defaultrequired", _question[0].Attribute("defaultrequired").Value),
            new XAttribute("excluded", chkboxObj.Checked ? "true" : "false"));

        strQuizAssignment = xDocQuizAssignment.ToString();
    }

    protected void ddlistDifficulty_SelectedIndexChanged(object sender, EventArgs e)
    {
        DropDownList dropDownList = (DropDownList)sender;
        string SelectedDifficulty = dropDownList.SelectedItem.Value;

        int LearnObjID = Convert.ToInt32(dropDownList.ToolTip.Split(';')[0].ToString());
        int QuestionID = Convert.ToInt32(dropDownList.ToolTip.Split(';')[1].ToString());

        XDocument xDocQuizAssignment = new XDocument();
        if (strQuizAssignment != String.Empty)
            xDocQuizAssignment = XDocument.Parse(strQuizAssignment);

        List<XElement> _question = xDocQuizAssignment.Descendants("question").Where(
                    el => (int)el.Attribute("id") == QuestionID && (int)el.Attribute("learnobjid") == LearnObjID).ToList();

        _question[0].ReplaceAttributes(
           new XAttribute("learnobjid", LearnObjID.ToString()),
           new XAttribute("id", QuestionID.ToString()),
           new XAttribute("difficulty", SelectedDifficulty.ToString()),
           new XAttribute("point", _question[0].Attribute("point").Value),
           new XAttribute("defaultrequired", _question[0].Attribute("defaultrequired").Value),
           new XAttribute("excluded", _question[0].Attribute("excluded").Value));

        strQuizAssignment = xDocQuizAssignment.ToString();
    }

    protected void ddlistDifficulty_DataBound(object sender, EventArgs e)
    {
        DropDownList dropDownList = (DropDownList)sender;

        int LearnObjID = Convert.ToInt32(dropDownList.ToolTip.Split(';')[0].ToString());
        int QuestionID = Convert.ToInt32(dropDownList.ToolTip.Split(';')[1].ToString());

        XDocument xDocQuizAssignment = new XDocument();
        if (strQuizAssignment != String.Empty)
            xDocQuizAssignment = XDocument.Parse(strQuizAssignment);

        List<XElement> _question = xDocQuizAssignment.Descendants("question").Where(
                    el => (int)el.Attribute("id") == QuestionID && (int)el.Attribute("learnobjid") == LearnObjID).ToList();

        dropDownList.Items.FindByValue(_question[0].Attribute("difficulty").Value).Selected = true;

        strQuizAssignment = xDocQuizAssignment.ToString();
    }

    protected void ddlistPoint_SelectedIndexChanged(object sender, EventArgs e)
    {
        DropDownList dropDownList = (DropDownList)sender;

        int LearnObjID = Convert.ToInt32(dropDownList.ToolTip.Split(';')[0].ToString());
        int QuestionID = Convert.ToInt32(dropDownList.ToolTip.Split(';')[1].ToString());
        int Point = dropDownList.SelectedIndex + 1;

        XDocument xDocQuizAssignment = new XDocument();
        if (strQuizAssignment != String.Empty)
            xDocQuizAssignment = XDocument.Parse(strQuizAssignment);

        List<XElement> _question = xDocQuizAssignment.Descendants("question").Where(
                    el => (int)el.Attribute("id") == QuestionID && (int)el.Attribute("learnobjid") == LearnObjID).ToList();

        _question[0].ReplaceAttributes(
           new XAttribute("learnobjid", LearnObjID.ToString()),
           new XAttribute("id", QuestionID.ToString()),
           new XAttribute("difficulty", _question[0].Attribute("difficulty").Value),
           new XAttribute("point", Point.ToString()),
           new XAttribute("defaultrequired", _question[0].Attribute("defaultrequired").Value),
           new XAttribute("excluded", _question[0].Attribute("excluded").Value));

        strQuizAssignment = xDocQuizAssignment.ToString();
    }

    protected void ddlistPoint_DataBound(object sender, EventArgs e)
    {
        DropDownList dropDownList = (DropDownList)sender;

        int LearnObjID = Convert.ToInt32(dropDownList.ToolTip.Split(';')[0].ToString());
        int QuestionID = Convert.ToInt32(dropDownList.ToolTip.Split(';')[1].ToString());

        XDocument xDocQuizAssignment = new XDocument();
        if (strQuizAssignment != String.Empty)
            xDocQuizAssignment = XDocument.Parse(strQuizAssignment);

        List<XElement> _question = xDocQuizAssignment.Descendants("question").Where(
                    el => (int)el.Attribute("id") == QuestionID && (int)el.Attribute("learnobjid") == LearnObjID).ToList();

        dropDownList.Items.FindByValue(_question[0].Attribute("point").Value).Selected = true;

        strQuizAssignment = xDocQuizAssignment.ToString();
    }

    #region Add Custom Questions

    protected void btnAddNewCustomQuestion_Click(object sender, EventArgs e)
    {
        int LearnObjID = 0;
        int QuestionID = 0;

        XDocument xDocQuizAssignment = new XDocument();
        if (strQuizAssignment != String.Empty)
            xDocQuizAssignment = XDocument.Parse(strQuizAssignment);

        try
        {
            QuestionID = Convert.ToInt32(xDocQuizAssignment.Descendants("question").Where(
                            el => (int)el.Attribute("learnobjid") == LearnObjID).Last().Attribute("id").Value);
        }
        catch { }

        QuestionID++;

        xDocQuizAssignment.Element("quizassignment").Element("questions").Add(
            new XElement("question", new XAttribute("learnobjid", LearnObjID.ToString()), new XAttribute("id", QuestionID.ToString()), new XAttribute("difficulty", "normal"), new XAttribute("point", "2"), new XAttribute("defaultrequired", "false"), new XAttribute("excluded", "false"),
                new XElement("questiontext", "New Custom Question"),
                new XElement("choices",
                    new XElement("choice", new XAttribute("iscorrectanswer", "true"), "Choice"))));

        strQuizAssignment = xDocQuizAssignment.ToString();
        FillCustomQuestionsList();
        ddlistCustomQuestionsList.SelectedIndex = ddlistCustomQuestionsList.Items.Count - 1;
        LoadCustomQuestion();

        strQuizAssignment = xDocQuizAssignment.ToString();
        PanelAddCustomQuestions.Visible = true;
    }

    protected void FillCustomQuestionsList()
    {
        XDocument xDocQuizAssignment = new XDocument();
        if (strQuizAssignment != String.Empty)
            xDocQuizAssignment = XDocument.Parse(strQuizAssignment);

        List<XElement> _list = xDocQuizAssignment.Descendants("question").Where(
            el => (int)el.Attribute("learnobjid") == 0).ToList();

        ddlistCustomQuestionsList.Items.Clear();

        if (_list.Count > 0)
        {
            foreach (XElement element in _list)
            {
                string question = element.Element("questiontext").Value;
                question = System.Text.RegularExpressions.Regex.Replace(question, "<br />", " ");
                question = System.Text.RegularExpressions.Regex.Replace(question, "&nbsp;", " ");
                question = System.Text.RegularExpressions.Regex.Replace(question, "<[^>]*>", String.Empty);
                if (question.Length > 60)
                {
                    question = question.Substring(0, 60);
                    question = question + "...";
                }
                ListItem newItem = new ListItem();
                newItem.Text = element.Attribute("id").Value + " - " + question;
                newItem.Value = element.Attribute("id").Value;
                ddlistCustomQuestionsList.Items.Add(newItem);
            }
        }
        else
        {
            // *SteveMsg
            ListItem newItem = new ListItem("No Custom Question", "0");
            ddlistCustomQuestionsList.Items.Add(newItem);
            PanelAddCustomQuestions.Visible = false;
        }

        strQuizAssignment = xDocQuizAssignment.ToString();
    }

    protected void ddlistCustomQuestionsList_SelectedIndexChanged(object sender, EventArgs e)
    {
        LoadCustomQuestion();
    }

    protected void LoadCustomQuestion()
    {
        int QuestionID = Convert.ToInt32(ddlistCustomQuestionsList.SelectedValue);

        XDocument xDocQuizAssignment = new XDocument();
        if (strQuizAssignment != String.Empty)
            xDocQuizAssignment = XDocument.Parse(strQuizAssignment);

        if (QuestionID != 0)
        {
            XElement question = xDocQuizAssignment.Descendants("question").Where(
                        el => (int)el.Attribute("id") == QuestionID && (int)el.Attribute("learnobjid") == 0).First();

            if (question.Attribute("defaultrequired").Value == "true")
                chkboxCustomQuestionRequired.Checked = true;
            else
                chkboxCustomQuestionRequired.Checked = false;

            switch (question.Attribute("difficulty").Value)
            {
                case "easy":
                    ddlistCustomQuestionDifficulty.SelectedIndex = 0;
                    break;
                case "normal":
                    ddlistCustomQuestionDifficulty.SelectedIndex = 1;
                    break;
                case "hard":
                    ddlistCustomQuestionDifficulty.SelectedIndex = 2;
                    break;
                default:
                    ddlistCustomQuestionDifficulty.SelectedIndex = 1;
                    break;
            }

            switch (question.Attribute("point").Value)
            {
                case "1":
                    ddlistCustomQuestionPoint.SelectedIndex = 0;
                    break;
                case "2":
                    ddlistCustomQuestionPoint.SelectedIndex = 1;
                    break;
                case "3":
                    ddlistCustomQuestionPoint.SelectedIndex = 2;
                    break;
                default:
                    ddlistCustomQuestionPoint.SelectedIndex = 1;
                    break;
            }

            txtCustomQuestionText.Value = question.Element("questiontext").Value;

            List<XElement> _choice = xDocQuizAssignment.Descendants("question").Descendants("choices").Descendants("choice").Where(
                el => (int)el.Parent.Parent.Attribute("id") == QuestionID && (int)el.Parent.Parent.Attribute("learnobjid") == 0).ToList();

            txtCustomQuestionChoice1.Text = String.Empty;
            chkCustomQuestionAnswer1.Checked = true;
            txtCustomQuestionChoice2.Text = String.Empty;
            chkCustomQuestionAnswer2.Checked = false;
            txtCustomQuestionChoice3.Text = String.Empty;
            chkCustomQuestionAnswer3.Checked = false;
            txtCustomQuestionChoice4.Text = String.Empty;
            chkCustomQuestionAnswer4.Checked = false;
            txtCustomQuestionChoice5.Text = String.Empty;
            chkCustomQuestionAnswer5.Checked = false;
            // Can Improve Code here by using FindControl
            if (_choice.Count >= 1)
            {
                txtCustomQuestionChoice1.Text = _choice[0].Value;
                chkCustomQuestionAnswer1.Checked = (_choice[0].Attribute("iscorrectanswer").Value == "true");
            }
            if (_choice.Count >= 2)
            {
                txtCustomQuestionChoice2.Text = _choice[1].Value;
                chkCustomQuestionAnswer2.Checked = (_choice[1].Attribute("iscorrectanswer").Value == "true");
            }
            if (_choice.Count >= 3)
            {
                txtCustomQuestionChoice3.Text = _choice[2].Value;
                chkCustomQuestionAnswer3.Checked = (_choice[2].Attribute("iscorrectanswer").Value == "true");
            }
            if (_choice.Count >= 4)
            {
                txtCustomQuestionChoice4.Text = _choice[3].Value;
                chkCustomQuestionAnswer4.Checked = (_choice[3].Attribute("iscorrectanswer").Value == "true");
            }
            if (_choice.Count == 5)
            {
                txtCustomQuestionChoice5.Text = _choice[4].Value;
                chkCustomQuestionAnswer5.Checked = (_choice[4].Attribute("iscorrectanswer").Value == "true");
            }
        }
        else
        {

        }

        strQuizAssignment = xDocQuizAssignment.ToString();
    }

    protected void btnUpdateCustomQuestion_Click(object sender, EventArgs e)
    {
        int LearnObjID = 0;
        int QuestionID = Convert.ToInt32(ddlistCustomQuestionsList.SelectedValue);

        XDocument xDocQuizAssignment = new XDocument();
        if (strQuizAssignment != String.Empty)
            xDocQuizAssignment = XDocument.Parse(strQuizAssignment);

        XElement question = xDocQuizAssignment.Descendants("question").First(
                    el => (int)el.Attribute("id") == QuestionID && (int)el.Attribute("learnobjid") == LearnObjID);

        question.ReplaceAttributes(new XAttribute("learnobjid", LearnObjID.ToString()),
            new XAttribute("id", QuestionID.ToString()),
            new XAttribute("difficulty", ddlistCustomQuestionDifficulty.SelectedValue),
            new XAttribute("point", ddlistCustomQuestionPoint.SelectedValue),
            new XAttribute("defaultrequired", chkboxCustomQuestionRequired.Checked ? "true" : "false"),
            new XAttribute("excluded", "false"));

        question.Element("questiontext").Value = txtCustomQuestionText.Value;

        question.Descendants("choice").Remove();

        XElement choices = question.Descendants("choices").First();

        bool flag_AtLeastOneAnswer = false;
        if (txtCustomQuestionChoice1.Text != String.Empty)
        {
            choices.Add(new XElement("choice", new XAttribute("iscorrectanswer", chkCustomQuestionAnswer1.Checked ? "true" : "false"), txtCustomQuestionChoice1.Text));
            if (flag_AtLeastOneAnswer == false)
            {
                flag_AtLeastOneAnswer = chkCustomQuestionAnswer1.Checked;
            }
        }
        if (txtCustomQuestionChoice2.Text != String.Empty)
        {
            choices.Add(new XElement("choice", new XAttribute("iscorrectanswer", chkCustomQuestionAnswer2.Checked ? "true" : "false"), txtCustomQuestionChoice2.Text));
            if (flag_AtLeastOneAnswer == false)
            {
                flag_AtLeastOneAnswer = chkCustomQuestionAnswer2.Checked;
            }
        }
        if (txtCustomQuestionChoice3.Text != String.Empty)
        {
            choices.Add(new XElement("choice", new XAttribute("iscorrectanswer", chkCustomQuestionAnswer3.Checked ? "true" : "false"), txtCustomQuestionChoice3.Text));
            if (flag_AtLeastOneAnswer == false)
            {
                flag_AtLeastOneAnswer = chkCustomQuestionAnswer3.Checked;
            }
        }
        if (txtCustomQuestionChoice4.Text != String.Empty)
        {
            choices.Add(new XElement("choice", new XAttribute("iscorrectanswer", chkCustomQuestionAnswer4.Checked ? "true" : "false"), txtCustomQuestionChoice4.Text));
            if (flag_AtLeastOneAnswer == false)
            {
                flag_AtLeastOneAnswer = chkCustomQuestionAnswer4.Checked;
            }
        }
        if (txtCustomQuestionChoice5.Text != String.Empty)
        {
            choices.Add(new XElement("choice", new XAttribute("iscorrectanswer", chkCustomQuestionAnswer5.Checked ? "true" : "false"), txtCustomQuestionChoice5.Text));
            if (flag_AtLeastOneAnswer == false)
            {
                flag_AtLeastOneAnswer = chkCustomQuestionAnswer5.Checked;
            }
        }

        if (flag_AtLeastOneAnswer == false)
        {
            string _message = "Please Check at least One Answer as correct.";
            ModalPopupMessage.ShowModalPopup("ILE Message", _message, 2);
        }
        else
        {
            strQuizAssignment = xDocQuizAssignment.ToString();
            FillCustomQuestionsList();
            ddlistCustomQuestionsList.SelectedValue = QuestionID.ToString();
            LoadCustomQuestion();
        }

        strQuizAssignment = xDocQuizAssignment.ToString();
    }

    protected void btnDeleteCustomQuestion_Click(object sender, EventArgs e)
    {
        int LearnObjID = 0;
        int QuestionID = Convert.ToInt32(ddlistCustomQuestionsList.SelectedValue);

        XDocument xDocQuizAssignment = new XDocument();
            if (strQuizAssignment != String.Empty)
                xDocQuizAssignment = XDocument.Parse(strQuizAssignment);

        try
        {
            xDocQuizAssignment.Descendants("question").Where(
                el => (int)el.Attribute("id") == QuestionID && (int)el.Attribute("learnobjid") == LearnObjID).First().Remove();
        }
        catch
        {
            string _message = "Failed to delete the Question.";
            ModalPopupMessage.ShowModalPopup("ILE Message", _message, 2);
            return;
        }

        int selectedIndex = ddlistCustomQuestionsList.SelectedIndex;
        FillCustomQuestionsList();
        ddlistCustomQuestionsList.SelectedIndex = selectedIndex - 1;
        LoadCustomQuestion();

        strQuizAssignment = xDocQuizAssignment.ToString();
    }

    #endregion

    #region Questions Overview

    protected void LoadQuestionsOverview()
    {
        int LearnObjID = Convert.ToInt32(ddlistQuestionsOverviewFilterByQuizSet.SelectedValue);

        XDocument xDocQuizAssignmentFiltered = XDocument.Parse(strQuizAssignment);

        switch (LearnObjID)
        {
            case -1: // SHOW ALL
                break;
            default:
                //var query = from c in xDocQuizAssignmentFiltered.Descendants("question")
                //            where (string)c.Attribute("learnobjid").Value != LearnObjID.ToString()
                //            select c;

                List<XElement> _questions = xDocQuizAssignmentFiltered.Descendants("question").Where(
                    el => (int)el.Attribute("learnobjid") != LearnObjID).ToList();

                foreach (XElement question in _questions)
                {
                    question.Remove();
                }
                break;
        }

        switch (Convert.ToInt32(rdbtnQuestionsOverviewFilter.SelectedValue))
        {
            case 1:
                xDocQuizAssignmentFiltered.Descendants("question").Where(
                        el => (string)el.Attribute("excluded").Value == "true").Remove();
                break;
            case 2:
                xDocQuizAssignmentFiltered.Descendants("question").Where(
                        el => (string)el.Attribute("excluded").Value == "true" ||
                            (string)el.Attribute("defaultrequired").Value == "false").Remove();
                break;
            case 3:
                xDocQuizAssignmentFiltered.Descendants("question").Where(
                        el => (string)el.Attribute("excluded").Value == "false" ||
                            (string)el.Attribute("defaultrequired").Value == "true").Remove();
                break;
            default:
                break;

        }

        XmlDataSourceQuestionsOverview.EnableCaching = false;
        XmlDataSourceQuestionsOverview.Data = xDocQuizAssignmentFiltered.ToString();
        XmlDataSourceQuestionsOverview.DataBind();

        RepeaterQuestionsOverview.DataBind();
    }

    protected void FillDdlistQuestionsOverviewFilterByQuizSet()
    {
        ddlistQuestionsOverviewFilterByQuizSet.Items.Add(new ListItem("Show All", "-1"));

        foreach (ListItem item in ddlistQuestionFilterByQuizSet.Items)
        {
            if (item.Value != "0")
                ddlistQuestionsOverviewFilterByQuizSet.Items.Add(item);
        }

        ddlistQuestionsOverviewFilterByQuizSet.Items.Add(new ListItem("Custom Questions", "0"));
    }

    protected void rdbtnQuestionsOverviewFilter_SelectedIndexChanged(object sender, EventArgs e)
    {
        LoadQuestionsOverview();
    }

    protected void ddlistQuestionsOverviewFilterByQuizSet_SelectedIndexChanged(object sender, EventArgs e)
    {
        LoadQuestionsOverview();
    }

    #endregion

    #region Last Step!

    protected void FillDdlistNumberOfQuestionsToGenerate()
    {
        ddlistGeneralNumberOfQuestionsToGenerate.Items.Clear();

        XDocument xDocQuizAssignment = new XDocument();
        if (strQuizAssignment != String.Empty)
            xDocQuizAssignment = XDocument.Parse(strQuizAssignment);

        int Minimum = xDocQuizAssignment.Descendants("question").Where(
                    el => (bool)el.Attribute("defaultrequired") == true).Count();
        if (Minimum == 0)
            Minimum++;

        int Maximum = xDocQuizAssignment.Descendants("question").Where(
                    el => (bool)el.Attribute("excluded") == false).Count();
        if (Maximum == 0)
        {
            WizardCreateQuizAssignment.ActiveStepIndex = 2;
            string _msg = "You cannot exclude all the questions!";
            ModalPopupMessage.ShowModalPopup("ILE Message", _msg, 2);
            return;
        }

        int iterator = Maximum - Minimum;

        for (int i = 0; iterator >= i; i++)
        {
            ddlistGeneralNumberOfQuestionsToGenerate.Items.Add(new ListItem(Minimum.ToString(), Minimum.ToString()));
            Minimum++;
        }

        strQuizAssignment = xDocQuizAssignment.ToString();
    }

    protected void chkboxGeneralSendNotificationEmail_CheckedChanged(object sender, EventArgs e)
    {
        if (chkboxGeneralSendNotificationEmail.Checked)
            PanelGeneralSendNotificationEmailOption.Visible = true;
        else
            PanelGeneralSendNotificationEmailOption.Visible = false;
    }

    protected void WizardCreateQuizAssignment_FinishButtonClick(object sender, EventArgs e)
    {
        AssignmentsBLL assignmentsLogic = new AssignmentsBLL();

        XDocument xDocQuizAssignment = new XDocument();
        if (strQuizAssignment != String.Empty)
            xDocQuizAssignment = XDocument.Parse(strQuizAssignment);

        string AssignmentName = txtGeneralQuizAssignmentName.Text;
        string AssignmentDirections = txtGeneralQuizAssignmentDirections.Value;

        if (AssignmentName.Trim().Length <= 0)
        {
            // *SteveMsg
            string _msg = "Assignment Name is Required.";
            ModalPopupMessage.ShowModalPopup("ILE Message", _msg, 2);
            return;
        }
        else
        {
            xDocQuizAssignment.Element("quizassignment").Attribute("name").SetValue(AssignmentName);
        }

        int MaximumAttempts = Convert.ToInt32(ddlistGeneralNumberOfAttempts.SelectedValue);
        int NumberOfQuestions = Convert.ToInt32(ddlistGeneralNumberOfQuestionsToGenerate.SelectedValue);

        if (txtGeneralStartDate.Text == String.Empty ||
            txtGeneralStartDateTime.Text == String.Empty ||
            txtGeneralEndDate.Text == String.Empty ||
            txtGeneralEndDateTime.Text == String.Empty)
        {
            // *SteveMsg
            string _msg = "Please Enter Start and End Date Times.";
            ModalPopupMessage.ShowModalPopup("ILE Message", _msg, 2);
            return;
        }

        if (chkboxGeneralSendNotificationEmail.Checked && txtGeneralSendNotificationEmailQuizEndHours.Text == String.Empty)
        {
            txtGeneralSendNotificationEmailQuizEndHours.Text = "24";
        }

        DateTime StartDateTime = new DateTime();
        DateTime EndDateTime = new DateTime();

        try
        {
            StartDateTime = Convert.ToDateTime(txtGeneralStartDate.Text + " " + txtGeneralStartDateTime.Text);
            EndDateTime = Convert.ToDateTime(txtGeneralEndDate.Text + " " + txtGeneralEndDateTime.Text);
        }
        catch
        {
            // *SteveMsg
            string _msg = "Please Enter Valid Start and End Date Times.";
            ModalPopupMessage.ShowModalPopup("ILE Message", _msg, 2);
            return;
        }

        int EndDateTimeHours = Convert.ToInt32(txtGeneralSendNotificationEmailQuizEndHours.Text);

        bool SendNotify = chkboxGeneralSendNotificationEmail.Checked;
        bool SendNotifyStart = false;
        bool SendNotifyEnd = false;
        bool SendResult = chkboxGeneralSendQuizResult.Checked;

        if (SendNotify)
        {
            SendNotifyStart = chkboxGeneralSendNotificationEmailQuizStart.Checked;
            SendNotifyEnd = chkboxGeneralSendNotificationEmailQuizEnd.Checked;
        }

        int AssignmentID = assignmentsLogic.InsertQuizAssignment(AssignmentName, AssignmentDirections, xDocQuizAssignment.ToString(), MaximumAttempts,
            NumberOfQuestions, SendNotifyStart, SendNotifyEnd, EndDateTimeHours, SendResult, StartDateTime, EndDateTime);

        bool result = AssignmentID != 0;
        if (result)
        {
            foreach (ListItem item in lstboxSections.Items)
            {
                if (item.Selected)
                {
                    bool result2 = assignmentsLogic.InsertRelation(AssignmentID, CourseID, Convert.ToInt32(item.Value), StandardID);
                    if (!result2)
                    {
                        try
                        {
                            assignmentsLogic.DeleteAssignment(AssignmentID);
                        }
                        catch
                        {
                            // Nothing needed.
                        }
                        result = false;
                        ileGlobal.RecordError("Admin/Assignment_Quiz.aspx.cs:WizardCreateQuizAssignment_FinishButtonClick:000", "Inserted Quiz Assignment but failed to insert relations.", 1, Request.Browser);
                    }
                }
            }

            ScheduledEmailsToSendBLL autoemailLogic = new ScheduledEmailsToSendBLL();

            if (SendNotifyStart)
            {
                autoemailLogic.InsertScheduledEmailToSend(AssignmentID, "Starts", CourseID, SectionNumber, StartDateTime);
            }

            if (SendNotifyEnd)
            {
                autoemailLogic.InsertScheduledEmailToSend(AssignmentID, "BeforeDue", CourseID, SectionNumber, EndDateTime.AddHours(-EndDateTimeHours));
            }

            if (SendResult)
            {
                autoemailLogic.InsertScheduledEmailToSend(AssignmentID, "Results", CourseID, SectionNumber, EndDateTime);
            }
        }
        else
        {
            ileGlobal.RecordError("Admin/Assignment_Quiz.aspx.cs:WizardCreateQuizAssignment_FinishButtonClick:001", "failed to insert quiz assignment.", 1, Request.Browser);
        }

        if (result)
        {
            // *SteveMsg
            string _message = "Quiz successfully assigned.";
            ModalPopupMessage.ShowModalPopup_Redirect("ILE Message", _message, 1, "Assignments_Quiz.aspx");
        }
        else
        {
            // *SteveMsg
            string _message = "Failed to assign the Quiz.";
            ModalPopupMessage.ShowModalPopup("ILE Message", _message, 2);
        }
    }

    #endregion


    #region Edit Quiz Assignment

    protected void WizardEditQuizAssignment_ActiveStepChanged(object sender, EventArgs e)
    {
        if (WizardEditQuizAssignment.ActiveStepIndex == 0)
        {
            strQuizAssignment = String.Empty;
            // Hide Selected Sections when User comes back to this step
            lblEditQuizSelectedSections.Text = "Selected Sections: ";
            lblEditQuizSelectedSections.Visible = false;

        }
        else if (WizardEditQuizAssignment.ActiveStepIndex == 1)
        {
            XDocument xDocQuizAssignment = new XDocument();
            if (strQuizAssignment != String.Empty)
                xDocQuizAssignment = XDocument.Parse(strQuizAssignment);

            if (GridViewAssignments.SelectedIndex == -1)
            {
                WizardEditQuizAssignment.ActiveStepIndex = 0;
                // *SteveMsg
                string _msg = "You must select a quiz to edit.";
                ModalPopupMessage.ShowModalPopup("ILE Message", _msg, 2);
                return;
            }
            else
            {
                if (lstboxEditSections.SelectedIndex == -1)
                {
                    WizardEditQuizAssignment.ActiveStepIndex = 0;
                    // *SteveMsg
                    string _msg = "At least 1 section must be selected from the 'Sections' Listbox.";
                    ModalPopupMessage.ShowModalPopup("ILE Message", _msg, 2);
                }
                else
                {
                    // Showing Selected Sections
                    {
                        foreach (ListItem item in lstboxEditSections.Items)
                        {
                            if (item.Selected)
                                lblEditQuizSelectedSections.Text += item.Value.ToString() + ", ";
                        }

                        lblEditQuizSelectedSections.Text = lblEditQuizSelectedSections.Text.Substring(0, lblEditQuizSelectedSections.Text.Length - 2);
                        lblEditQuizSelectedSections.Visible = true;
                    }

                    AssignmentsBLL assignmentsLogic = new AssignmentsBLL();

                    int AssignmentID = Convert.ToInt32(GridViewAssignments.SelectedValue);
                    Assignments.Assignments_QuizRow assignmentQuiz = assignmentsLogic.GetAssignmentQuizByAssignmentID(AssignmentID);

                    xDocQuizAssignment.Declaration = new XDeclaration("1.0", "utf-8", "yes");
                    xDocQuizAssignment = XDocument.Parse(assignmentQuiz.QuizAssignment);

                    strQuizAssignment = xDocQuizAssignment.ToString();

                    XmlDataSourceEditQuestions.EnableCaching = false;
                    XmlDataSourceEditQuestions.Data = xDocQuizAssignment.ToString();
                    XmlDataSourceEditQuestions.DataBind();

                    strQuizAssignment = xDocQuizAssignment.ToString();

                    RepeaterEditQuestions.DataBind();

                    FillddlistEditQuestionFilterByQuizSet();

                    StandardID = Convert.ToInt32(RadioButtonListEditStandardID.SelectedValue);
                }
            }
            strQuizAssignment = xDocQuizAssignment.ToString();
        }
        else if (WizardEditQuizAssignment.ActiveStepIndex == 2)
        {
            XDocument xDocQuizAssignment = new XDocument();
            if (strQuizAssignment != String.Empty)
                xDocQuizAssignment = XDocument.Parse(strQuizAssignment);

            List<XElement> _questions = xDocQuizAssignment.Descendants("question").Where(
                    el => (int)el.Attribute("learnobjid") == 0).ToList();
            if (_questions.Count != 0)
            {
                FillEditCustomQuestionsList();
            }
            strQuizAssignment = xDocQuizAssignment.ToString();
        }
        else if (WizardEditQuizAssignment.ActiveStepIndex == 3)
        {
            FillDdlistEditQuestionsOverviewFilterByQuizSet();
            LoadEditQuestionsOverview();
        }
        else if (WizardEditQuizAssignment.ActiveStepIndex == 4)
        {
            LoadDataForEditQuizGeneral();
        }
    }

    protected void WizardEditQuizAssignment_NextButtonClick(object sender, WizardNavigationEventArgs e)
    {
        if (e.NextStepIndex == 2)
        {
            WizardEditQuizAssignment.ActiveStepIndex = 4;
        }
    }

    protected void GridViewAssignments_SelectedIndexChanged(object sender, EventArgs e)
    {
        AssignmentsBLL assignmentsLogic = new AssignmentsBLL();
        GridView grdview = (GridView)sender;
        //if (grdview.SelectedIndex != -1)
        
            int AssignmentID = Convert.ToInt32(grdview.SelectedValue);
            if (AssignmentID == 0)
            {
                AssignmentID = Convert.ToInt32(grdview.SelectedValue);
            }
            Assignments.RelationsDataTable relations = assignmentsLogic.GetRelationsByAssignmentID(AssignmentID);
            try
            {
                CourseID = relations[0].CourseID;
                int tempStandardID = relations[0].StandardID;
                ClassBLL classLogic = new ClassBLL();
                lblEditClass.Text = classLogic.GetCourse(CourseID).Title;

                FillLstboxEditSections(CourseID);

                foreach (ListItem item in lstboxEditSections.Items)
                {
                    foreach (Assignments.RelationsRow relation in relations)
                    {
                        if (item.Value == relation.SectionNumber.ToString())
                            item.Selected = true;
                    }
                }

                foreach (ListItem item in RadioButtonListEditStandardID.Items)
                {
                    if (item.Value == tempStandardID.ToString())
                    {
                        item.Selected = true;
                        break;
                    }
                }
            }
            catch (IndexOutOfRangeException ex)
            {
                ModalPopupMessage.ShowModalPopup("ILE Urgent Message", "This Assignment is corrupted and recommended to be deleted.", 2);
                ileGlobal.RecordError("Assignment_Quiz.aspx.cs", ex, 1, Request.Browser);
            }

            WizardEditQuizAssignment.NavigationStyle.CssClass = "";
            PanelEditQuizSections.Visible = true;
        //}
        //else
        //{
        //    WizardEditQuizAssignment.NavigationStyle.CssClass = "Hidden";
        //}
    }

    protected void FillLstboxEditSections(int CourseID)
    {
        lstboxEditSections.Items.Clear();
        ClassBLL classLogic = new ClassBLL();
        Classes.Courses_SectionDataTable sections = classLogic.GetSectionsByCourseID(CourseID, false);
        foreach (Classes.Courses_SectionRow section in sections)
        {
            lstboxEditSections.Items.Add(new ListItem(section.SectionNumber.ToString(), section.SectionNumber.ToString()));
        }
    }

    protected void btnEditJumpToDetails_Click(object sender, EventArgs e)
    {
        XDocument xDocQuizAssignment = new XDocument();
        if (strQuizAssignment != String.Empty)
            xDocQuizAssignment = XDocument.Parse(strQuizAssignment);

        if (lstboxEditSections.SelectedIndex == -1)
        {
            WizardEditQuizAssignment.ActiveStepIndex = 0;
            // *SteveMsg
            string _msg = "At least 1 section must be selected from the 'Sections' Listbox.";
            ModalPopupMessage.ShowModalPopup("ILE Message", _msg, 2);
        }
        else
        {
            AssignmentsBLL assignmentsLogic = new AssignmentsBLL();

            int AssignmentID = Convert.ToInt32(GridViewAssignments.SelectedValue);
            Assignments.Assignments_QuizRow assignmentQuiz = assignmentsLogic.GetAssignmentQuizByAssignmentID(AssignmentID);

            xDocQuizAssignment.Declaration = new XDeclaration("1.0", "utf-8", "yes");
            xDocQuizAssignment = XDocument.Parse(assignmentQuiz.QuizAssignment);

            strQuizAssignment = xDocQuizAssignment.ToString();

            XmlDataSourceEditQuestions.EnableCaching = false;
            XmlDataSourceEditQuestions.Data = xDocQuizAssignment.ToString();
            XmlDataSourceEditQuestions.DataBind();

            RepeaterEditQuestions.DataBind();

            FillddlistEditQuestionFilterByQuizSet();

            StandardID = Convert.ToInt32(RadioButtonListEditStandardID.SelectedValue);
        }

        strQuizAssignment = xDocQuizAssignment.ToString();

        WizardEditQuizAssignment.ActiveStepIndex = 4;
    }

    #region Edit Choose Required and Excluded

    protected void FillddlistEditQuestionFilterByQuizSet()
    {
        XDocument xDocQuizAssignment = new XDocument();
        if (strQuizAssignment != String.Empty)
            xDocQuizAssignment = XDocument.Parse(strQuizAssignment);

        List<XElement> _questions = xDocQuizAssignment.Descendants("question").Where(
                    el => (int)el.Attribute("learnobjid") != -1).ToList();
        List<int> _learnObjIDs = new List<int>();

        int tempLearnObjID = 0;
        foreach (XElement question in _questions)
        {
            tempLearnObjID = Convert.ToInt32(question.Attribute("learnobjid").Value);
            if (_learnObjIDs.Count != 0)
            {
                if (_learnObjIDs.Last() != tempLearnObjID)
                    _learnObjIDs.Add(tempLearnObjID);
            }
            else
            {
                _learnObjIDs.Add(tempLearnObjID);
            }
        }

        ddlistEditQuestionFilterByQuizSet.Items.Clear();
        ddlistEditQuestionFilterByQuizSet.Items.Add(new ListItem("Show All", "-1"));

        foreach (int learnObjID in _learnObjIDs)
        {
            if (learnObjID == 0)
            {
                ddlistEditQuestionFilterByQuizSet.Items.Add(new ListItem("Custom Questions", learnObjID.ToString()));
            }
            else
            {
                LearnObjsBLL learnObjsLogic = new LearnObjsBLL();
                LearnObjs.LearnObjsRow tempLearnObj = learnObjsLogic.GetLearnObj(learnObjID);
                ddlistEditQuestionFilterByQuizSet.Items.Add(new ListItem("Quiz for " + tempLearnObj.Title, learnObjID.ToString()));
            }
        }

        strQuizAssignment = xDocQuizAssignment.ToString();
    }

    protected void ddlistEditQuestionFilterByQuizSet_SelectedIndexChanged(object sender, EventArgs e)
    {
        // FILTER
        switch (((DropDownList)sender).SelectedIndex)
        {
            case 0:
                XmlDataSourceQuestions.EnableCaching = false;
                XmlDataSourceEditQuestions.Data = strQuizAssignment.ToString();
                XmlDataSourceEditQuestions.DataBind();
                RepeaterEditQuestions.DataBind();
                break;
            default:
                int LearnObjID = Convert.ToInt32(((DropDownList)sender).SelectedValue);
                XDocument xDocQuizAssignmentFiltered = XDocument.Parse(strQuizAssignment);

                //var query = from c in xDocQuizAssignmentFiltered.Descendants("question")
                //            where (string)c.Attribute("learnobjid").Value != LearnObjID.ToString()
                //            select c;

                List<XElement> _questions = xDocQuizAssignmentFiltered.Descendants("question").Where(
                    el => (int)el.Attribute("learnobjid") != LearnObjID).ToList();

                foreach (XElement question in _questions)
                {
                    question.Remove();
                }

                XmlDataSourceEditQuestions.EnableCaching = false;
                XmlDataSourceEditQuestions.Data = xDocQuizAssignmentFiltered.ToString();
                XmlDataSourceEditQuestions.DataBind();
                RepeaterEditQuestions.DataBind();
                break;
        }
    }

    protected void chkboxQuizEditRequired_CheckedChanged(object sender, EventArgs e)
    {
        CheckBox chkboxObj = (CheckBox)sender;
        string[] arguments = new string[2];
        arguments = chkboxObj.Text.Split(';');
        int LearnObjID = Convert.ToInt32(arguments[0]);
        int QuestionID = Convert.ToInt32(arguments[1]);

        XDocument xDocQuizAssignment = new XDocument();
        if (strQuizAssignment != String.Empty)
            xDocQuizAssignment = XDocument.Parse(strQuizAssignment);

        //var query = from c in xDocQuizAssignment.Elements("quizassignment").Elements("questions").Elements("question")
        //            where (string)c.Attribute("learnobjid").Value == LearnObjID.ToString() &&
        //                  (string)c.Attribute("id").Value == LearnObjID.ToString()
        //            select c;

        XElement question = xDocQuizAssignment.Descendants("question").First(
                    el => (int)el.Attribute("learnobjid") == LearnObjID && (int)el.Attribute("id") == QuestionID);

        question.Attribute("defaultrequired").Value = chkboxObj.Checked ? "true" : "false";
        question.ReplaceAttributes(
            new XAttribute("learnobjid", LearnObjID.ToString()),
            new XAttribute("id", QuestionID.ToString()),
            new XAttribute("difficulty", question.Attribute("difficulty").Value),
            new XAttribute("point", question.Attribute("point").Value),
            new XAttribute("defaultrequired", chkboxObj.Checked ? "true" : "false"),
            new XAttribute("excluded", question.Attribute("excluded").Value));

        strQuizAssignment = xDocQuizAssignment.ToString();
    }

    protected void chkboxQuizEditExcluded_CheckedChanged(object sender, EventArgs e)
    {
        CheckBox chkboxObj = (CheckBox)sender;
        string[] arguments = new string[2];
        arguments = chkboxObj.Text.Split(';');
        int LearnObjID = Convert.ToInt32(arguments[0]);
        int QuestionID = Convert.ToInt32(arguments[1]);

        XDocument xDocQuizAssignment = new XDocument();
        if (strQuizAssignment != String.Empty)
            xDocQuizAssignment = XDocument.Parse(strQuizAssignment);

        List<XElement> _question = xDocQuizAssignment.Descendants("question").Where(
                    el => (int)el.Attribute("id") == QuestionID && (int)el.Attribute("learnobjid") == LearnObjID).ToList();
        _question[0].ReplaceAttributes(
            new XAttribute("learnobjid", LearnObjID.ToString()),
            new XAttribute("id", QuestionID.ToString()),
            new XAttribute("difficulty", _question[0].Attribute("difficulty").Value),
            new XAttribute("point", _question[0].Attribute("point").Value),
            new XAttribute("defaultrequired", _question[0].Attribute("defaultrequired").Value),
            new XAttribute("excluded", chkboxObj.Checked ? "true" : "false"));

        strQuizAssignment = xDocQuizAssignment.ToString();
    }

    protected void btnEditQuizJumpToAddCustomQuestions_Click(object sender, EventArgs e)
    {
        WizardEditQuizAssignment.ActiveStepIndex = 2;
    }

    #endregion

    #region Edit Custom Questions

    protected void btnEditAddNewCustomQuestion_Click(object sender, EventArgs e)
    {
        int LearnObjID = 0;
        int QuestionID = 0;

        XDocument xDocQuizAssignment = new XDocument();
        if (strQuizAssignment != String.Empty)
            xDocQuizAssignment = XDocument.Parse(strQuizAssignment);

        try
        {
            QuestionID = Convert.ToInt32(xDocQuizAssignment.Descendants("question").Where(
                            el => (int)el.Attribute("learnobjid") == LearnObjID).Last().Attribute("id").Value);
        }
        catch { }

        QuestionID++;

        xDocQuizAssignment.Element("quizassignment").Element("questions").Add(
            new XElement("question", new XAttribute("learnobjid", LearnObjID.ToString()), new XAttribute("id", QuestionID.ToString()), new XAttribute("difficulty", "normal"), new XAttribute("point", "2"), new XAttribute("defaultrequired", "false"), new XAttribute("excluded", "false"),
                new XElement("questiontext", "New Custom Question"),
                new XElement("choices",
                    new XElement("choice", new XAttribute("iscorrectanswer", "true"), "Choice"))));


        FillEditCustomQuestionsList();
        ddlistEditCustomQuestionsList.SelectedIndex = ddlistEditCustomQuestionsList.Items.Count - 1;
        LoadEditCustomQuestion();

        strQuizAssignment = xDocQuizAssignment.ToString();

        PanelEditAddCustomQuestions.Visible = true;
    }

    protected void FillEditCustomQuestionsList()
    {
        XDocument xDocQuizAssignment = new XDocument();
        if (strQuizAssignment != String.Empty)
            xDocQuizAssignment = XDocument.Parse(strQuizAssignment);

        List<XElement> _list = xDocQuizAssignment.Descendants("question").Where(
            el => (int)el.Attribute("learnobjid") == 0).ToList();

        ddlistEditCustomQuestionsList.Items.Clear();

        if (_list.Count > 0)
        {
            foreach (XElement element in _list)
            {
                string question = element.Element("questiontext").Value;
                question = System.Text.RegularExpressions.Regex.Replace(question, "<br />", " ");
                question = System.Text.RegularExpressions.Regex.Replace(question, "&nbsp;", " ");
                question = System.Text.RegularExpressions.Regex.Replace(question, "<[^>]*>", String.Empty);
                if (question.Length > 60)
                {
                    question = question.Substring(0, 60);
                    question = question + "...";
                }
                ListItem newItem = new ListItem();
                newItem.Text = element.Attribute("id").Value + " - " + question;
                newItem.Value = element.Attribute("id").Value;
                ddlistEditCustomQuestionsList.Items.Add(newItem);
            }
            PanelEditAddCustomQuestions.Visible = true;
        }
        else
        {
            // *SteveMsg
            ListItem newItem = new ListItem("No Custom Question", "0");
            ddlistEditCustomQuestionsList.Items.Add(newItem);
            PanelEditAddCustomQuestions.Visible = false;
        }

        strQuizAssignment = xDocQuizAssignment.ToString();
    }

    protected void ddlistEditCustomQuestionsList_SelectedIndexChanged(object sender, EventArgs e)
    {
        LoadEditCustomQuestion();
    }

    protected void LoadEditCustomQuestion()
    {
        int QuestionID = Convert.ToInt32(ddlistEditCustomQuestionsList.SelectedValue);

        XDocument xDocQuizAssignment = new XDocument();
        if (strQuizAssignment != String.Empty)
            xDocQuizAssignment = XDocument.Parse(strQuizAssignment);

        if (QuestionID != 0)
        {
            XElement question = xDocQuizAssignment.Descendants("question").Where(
                        el => (int)el.Attribute("id") == QuestionID && (int)el.Attribute("learnobjid") == 0).First();

            if (question.Attribute("defaultrequired").Value == "true")
                chkboxEditCustomQuestionRequired.Checked = true;
            else
                chkboxEditCustomQuestionRequired.Checked = false;

            switch (question.Attribute("difficulty").Value)
            {
                case "easy":
                    ddlistEditCustomQuestionDifficulty.SelectedIndex = 0;
                    break;
                case "normal":
                    ddlistEditCustomQuestionDifficulty.SelectedIndex = 1;
                    break;
                case "hard":
                    ddlistEditCustomQuestionDifficulty.SelectedIndex = 2;
                    break;
                default:
                    ddlistEditCustomQuestionDifficulty.SelectedIndex = 1;
                    break;
            }

            switch (question.Attribute("point").Value)
            {
                case "1":
                    ddlistEditCustomQuestionPoint.SelectedIndex = 0;
                    break;
                case "2":
                    ddlistEditCustomQuestionPoint.SelectedIndex = 1;
                    break;
                case "3":
                    ddlistEditCustomQuestionPoint.SelectedIndex = 2;
                    break;
                default:
                    ddlistEditCustomQuestionPoint.SelectedIndex = 1;
                    break;
            }

            txtEditCustomQuestionText.Value = question.Element("questiontext").Value;

            List<XElement> _choice = xDocQuizAssignment.Descendants("question").Descendants("choices").Descendants("choice").Where(
                el => (int)el.Parent.Parent.Attribute("id") == QuestionID && (int)el.Parent.Parent.Attribute("learnobjid") == 0).ToList();

            txtEditCustomQuestionChoice1.Text = String.Empty;
            chkEditCustomQuestionAnswer1.Checked = true;
            txtEditCustomQuestionChoice2.Text = String.Empty;
            chkEditCustomQuestionAnswer2.Checked = false;
            txtEditCustomQuestionChoice3.Text = String.Empty;
            chkEditCustomQuestionAnswer3.Checked = false;
            txtEditCustomQuestionChoice4.Text = String.Empty;
            chkEditCustomQuestionAnswer4.Checked = false;
            txtEditCustomQuestionChoice5.Text = String.Empty;
            chkEditCustomQuestionAnswer5.Checked = false;
            // Can Improve Code here by using FindControl
            if (_choice.Count >= 1)
            {
                txtEditCustomQuestionChoice1.Text = _choice[0].Value;
                chkEditCustomQuestionAnswer1.Checked = (_choice[0].Attribute("iscorrectanswer").Value == "true");
            }
            if (_choice.Count >= 2)
            {
                txtEditCustomQuestionChoice2.Text = _choice[1].Value;
                chkEditCustomQuestionAnswer2.Checked = (_choice[1].Attribute("iscorrectanswer").Value == "true");
            }
            if (_choice.Count >= 3)
            {
                txtEditCustomQuestionChoice3.Text = _choice[2].Value;
                chkEditCustomQuestionAnswer3.Checked = (_choice[2].Attribute("iscorrectanswer").Value == "true");
            }
            if (_choice.Count >= 4)
            {
                txtEditCustomQuestionChoice4.Text = _choice[3].Value;
                chkEditCustomQuestionAnswer4.Checked = (_choice[3].Attribute("iscorrectanswer").Value == "true");
            }
            if (_choice.Count == 5)
            {
                txtEditCustomQuestionChoice5.Text = _choice[4].Value;
                chkEditCustomQuestionAnswer5.Checked = (_choice[4].Attribute("iscorrectanswer").Value == "true");
            }
        }
        else
        {

        }

        strQuizAssignment = xDocQuizAssignment.ToString();
    }

    protected void btnEditUpdateCustomQuestion_Click(object sender, EventArgs e)
    {
        int LearnObjID = 0;
        int QuestionID = Convert.ToInt32(ddlistEditCustomQuestionsList.SelectedValue);

        XDocument xDocQuizAssignment = new XDocument();
        if (strQuizAssignment != String.Empty)
            xDocQuizAssignment = XDocument.Parse(strQuizAssignment);

        XElement question = xDocQuizAssignment.Descendants("question").First(
                    el => (int)el.Attribute("id") == QuestionID && (int)el.Attribute("learnobjid") == LearnObjID);

        question.ReplaceAttributes(new XAttribute("learnobjid", LearnObjID.ToString()),
            new XAttribute("id", QuestionID.ToString()),
            new XAttribute("difficulty", ddlistEditCustomQuestionDifficulty.SelectedValue),
            new XAttribute("point", ddlistEditCustomQuestionPoint.SelectedValue),
            new XAttribute("defaultrequired", chkboxEditCustomQuestionRequired.Checked ? "true" : "false"),
            new XAttribute("excluded", "false"));

        question.Element("questiontext").Value = txtEditCustomQuestionText.Value;

        question.Descendants("choice").Remove();

        XElement choices = question.Descendants("choices").First();

        bool flag_AtLeastOneAnswer = false;
        if (txtEditCustomQuestionChoice1.Text != String.Empty)
        {
            choices.Add(new XElement("choice", new XAttribute("iscorrectanswer", chkEditCustomQuestionAnswer1.Checked ? "true" : "false"), txtCustomQuestionChoice1.Text));
            if (flag_AtLeastOneAnswer == false)
            {
                flag_AtLeastOneAnswer = chkEditCustomQuestionAnswer1.Checked;
            }
        }
        if (txtEditCustomQuestionChoice2.Text != String.Empty)
        {
            choices.Add(new XElement("choice", new XAttribute("iscorrectanswer", chkEditCustomQuestionAnswer2.Checked ? "true" : "false"), txtCustomQuestionChoice2.Text));
            if (flag_AtLeastOneAnswer == false)
            {
                flag_AtLeastOneAnswer = chkEditCustomQuestionAnswer2.Checked;
            }
        }
        if (txtEditCustomQuestionChoice3.Text != String.Empty)
        {
            choices.Add(new XElement("choice", new XAttribute("iscorrectanswer", chkEditCustomQuestionAnswer3.Checked ? "true" : "false"), txtCustomQuestionChoice3.Text));
            if (flag_AtLeastOneAnswer == false)
            {
                flag_AtLeastOneAnswer = chkEditCustomQuestionAnswer3.Checked;
            }
        }
        if (txtEditCustomQuestionChoice4.Text != String.Empty)
        {
            choices.Add(new XElement("choice", new XAttribute("iscorrectanswer", chkEditCustomQuestionAnswer4.Checked ? "true" : "false"), txtCustomQuestionChoice4.Text));
            if (flag_AtLeastOneAnswer == false)
            {
                flag_AtLeastOneAnswer = chkCustomQuestionAnswer4.Checked;
            }
        }
        if (txtEditCustomQuestionChoice5.Text != String.Empty)
        {
            choices.Add(new XElement("choice", new XAttribute("iscorrectanswer", chkEditCustomQuestionAnswer5.Checked ? "true" : "false"), txtCustomQuestionChoice5.Text));
            if (flag_AtLeastOneAnswer == false)
            {
                flag_AtLeastOneAnswer = chkEditCustomQuestionAnswer5.Checked;
            }
        }

        if (flag_AtLeastOneAnswer == false)
        {
            string _message = "Please Check at least One Answer.";
            ModalPopupMessage.ShowModalPopup("ILE Message", _message, 2);
        }
        else
        {
            FillEditCustomQuestionsList();
            ddlistEditCustomQuestionsList.SelectedValue = QuestionID.ToString();
            LoadEditCustomQuestion();
        }

        strQuizAssignment = xDocQuizAssignment.ToString();
    }

    protected void btnEditDeleteCustomQuestion_Click(object sender, EventArgs e)
    {
        int LearnObjID = 0;
        int QuestionID = Convert.ToInt32(ddlistEditCustomQuestionsList.SelectedValue);

        XDocument xDocQuizAssignment = new XDocument();
        if (strQuizAssignment != String.Empty)
            xDocQuizAssignment = XDocument.Parse(strQuizAssignment);

        try
        {
            xDocQuizAssignment.Descendants("question").Where(
                el => (int)el.Attribute("id") == QuestionID && (int)el.Attribute("learnobjid") == LearnObjID).First().Remove();
        }
        catch
        {
            string _message = "Failed to delete the Question.";
            ModalPopupMessage.ShowModalPopup("ILE Message", _message, 2);
            return;
        }

        int selectedIndex = ddlistEditCustomQuestionsList.SelectedIndex;
        FillEditCustomQuestionsList();
        ddlistEditCustomQuestionsList.SelectedIndex = selectedIndex - 1;
        LoadEditCustomQuestion();

        strQuizAssignment = xDocQuizAssignment.ToString();
    }

    #endregion

    #region Edit Questions Overview

    protected void LoadEditQuestionsOverview()
    {
        int LearnObjID = Convert.ToInt32(ddlistEditQuestionsOverviewFilterByQuizSet.SelectedValue);

        XDocument xDocQuizAssignmentFiltered = XDocument.Parse(strQuizAssignment);

        switch (LearnObjID)
        {
            case -1: // SHOW ALL
                break;
            default:
                List<XElement> _questions = xDocQuizAssignmentFiltered.Descendants("question").Where(
                    el => (int)el.Attribute("learnobjid") != LearnObjID).ToList();

                foreach (XElement question in _questions)
                {
                    question.Remove();
                }
                break;
        }

        switch (Convert.ToInt32(rdbtnEditQuestionsOverviewFilter.SelectedValue))
        {
            case 1:
                xDocQuizAssignmentFiltered.Descendants("question").Where(
                        el => (string)el.Attribute("excluded").Value == "true").Remove();
                break;
            case 2:
                xDocQuizAssignmentFiltered.Descendants("question").Where(
                        el => (string)el.Attribute("excluded").Value == "true" ||
                            (string)el.Attribute("defaultrequired").Value == "false").Remove();
                break;
            case 3:
                xDocQuizAssignmentFiltered.Descendants("question").Where(
                        el => (string)el.Attribute("excluded").Value == "false" ||
                            (string)el.Attribute("defaultrequired").Value == "true").Remove();
                break;
            default:
                break;

        }

        XmlDataSourceEditQuestionsOverview.EnableCaching = false;
        XmlDataSourceEditQuestionsOverview.Data = xDocQuizAssignmentFiltered.ToString();
        XmlDataSourceEditQuestionsOverview.DataBind();

        RepeaterEditQuestionsOverview.DataBind();
    }

    protected void FillDdlistEditQuestionsOverviewFilterByQuizSet()
    {
        ddlistEditQuestionsOverviewFilterByQuizSet.Items.Clear();
        ddlistEditQuestionsOverviewFilterByQuizSet.Items.Add(new ListItem("Show All", "-1"));

        foreach (ListItem item in ddlistEditQuestionFilterByQuizSet.Items)
        {
            if (item.Value != "0")
                ddlistEditQuestionsOverviewFilterByQuizSet.Items.Add(item);
        }

        ddlistEditQuestionsOverviewFilterByQuizSet.Items.Add(new ListItem("Custom Questions", "0"));
    }

    protected void rdbtnEditQuestionsOverviewFilter_SelectedIndexChanged(object sender, EventArgs e)
    {
        LoadEditQuestionsOverview();
    }

    protected void ddlistEditQuestionsOverviewFilterByQuizSet_SelectedIndexChanged(object sender, EventArgs e)
    {
        LoadEditQuestionsOverview();
    }

    #endregion

    #region Edit General

    protected void chkboxEditQuizGeneralSendNotificationEmail_CheckedChanged(object sender, EventArgs e)
    {
        if (chkboxEditQuizGeneralSendNotificationEmail.Checked)
            PanelEditQuizGeneralSendNotificationEmailOption.Visible = true;
        else
            PanelEditQuizGeneralSendNotificationEmailOption.Visible = false;
    }

    protected void LoadDataForEditQuizGeneral()
    {
        FillDdlistEditQuizNumberOfQuestionsToGenerate();
        AssignmentsBLL assignmentsLogic = new AssignmentsBLL();

        int AssignmentID = Convert.ToInt32(GridViewAssignments.SelectedValue);
        Assignments.Assignments_QuizRow quizAssignment = assignmentsLogic.GetAssignmentQuizByAssignmentID(AssignmentID);

        ddlistEditQuizGeneralNumberOfQuestionsToGenerate.SelectedIndex = -1;
        foreach (ListItem item in ddlistEditQuizGeneralNumberOfQuestionsToGenerate.Items)
        {
            if (item == ddlistEditQuizGeneralNumberOfQuestionsToGenerate.Items.FindByValue(quizAssignment.NumberOfQuestions.ToString()))
            {
                item.Selected = true;
                break;
            }
        }

        LoadNumberOfAttempts();
        LoadQuizAssignmentSettings();
    }

    protected void FillDdlistEditQuizNumberOfQuestionsToGenerate()
    {
        ddlistEditQuizGeneralNumberOfQuestionsToGenerate.Items.Clear();

        XDocument xDocQuizAssignment = new XDocument();
        if (strQuizAssignment != String.Empty)
            xDocQuizAssignment = XDocument.Parse(strQuizAssignment);

        int Minimum = xDocQuizAssignment.Descendants("question").Where(
                    el => (bool)el.Attribute("defaultrequired") == true).Count();
        if (Minimum == 0)
        {
            Minimum++;
        }

        int Maximum = xDocQuizAssignment.Descendants("question").Where(
                    el => (bool)el.Attribute("excluded") == false).Count();
        if (Maximum == 0)
        {
            WizardCreateQuizAssignment.ActiveStepIndex = 2;
            string _msg = "You cannot exclude all the questions!";
            ModalPopupMessage.ShowModalPopup("ILE Message", _msg, 2);
            return;
        }

        int iterator = Maximum - Minimum;

        for (int i = 0; iterator >= i; i++)
        {
            ddlistEditQuizGeneralNumberOfQuestionsToGenerate.Items.Add(new ListItem(Minimum.ToString(), Minimum.ToString()));
            Minimum++;
        }

        strQuizAssignment = xDocQuizAssignment.ToString();
    }

    protected void LoadNumberOfAttempts()
    {
        AssignmentsBLL assignmentsLogic = new AssignmentsBLL();

        int AssignmentID = Convert.ToInt32(GridViewAssignments.SelectedValue);
        Assignments.Assignments_QuizRow quizAssignment = assignmentsLogic.GetAssignmentQuizByAssignmentID(AssignmentID);

        ddlistEditQuizGeneralNumberOfAttempts.SelectedIndex = -1;

        foreach (ListItem item in ddlistEditQuizGeneralNumberOfAttempts.Items)
        {
            if (item == ddlistEditQuizGeneralNumberOfAttempts.Items.FindByValue(quizAssignment.MaximumAttempts.ToString()))
            {
                item.Selected = true;
                break;
            }
        }
    }

    protected void LoadQuizAssignmentSettings()
    {
        AssignmentsBLL assignmentsLogic = new AssignmentsBLL();

        int AssignmentID = Convert.ToInt32(GridViewAssignments.SelectedValue);
        Assignments.AssignmentsRow assignment = assignmentsLogic.GetAssignmentByAssignmentID(AssignmentID);

        txtEditGeneralQuizAssignmentName.Text = assignment.AssignmentTitle;
        txtEditGeneralQuizAssignmentDirections.Value = assignment.Instruction;

        txtEditQuizGeneralStartDate.Text = assignment.StartDateTime.ToString("MM/dd/yyyy");
        txtEditQuizGeneralStartDateTime.Text = assignment.StartDateTime.ToString("hh:mm:ss tt");
        txtEditQuizGeneralEndDate.Text = assignment.EndDateTime.ToString("MM/dd/yyyy");
        txtEditQuizGeneralEndDateTime.Text = assignment.EndDateTime.ToString("hh:mm:ss tt");

        if (assignment.SendNotifyStart || assignment.SendNotifyEnd)
        {
            chkboxEditQuizGeneralSendNotificationEmail.Checked = true;
            PanelEditQuizGeneralSendNotificationEmailOption.Visible = true;
        }

        chkboxEditQuizGeneralSendNotificationEmailQuizStart.Checked = assignment.SendNotifyStart;
        chkboxEditQuizGeneralSendNotificationEmailQuizEnd.Checked = assignment.SendNotifyEnd;
        txtEditQuizGeneralSendNotificationEmailQuizEndHours.Text = assignment.SendNotifyEndHours.ToString();
        chkboxEditQuizGeneralSendQuizResult.Checked = assignment.SendResult;
    }

    protected void WizardEditQuizAssignment_FinishButtonClick(object sender, EventArgs e)
    {
        AssignmentsBLL assignmentsLogic = new AssignmentsBLL();

        int AssignmentID = Convert.ToInt32(GridViewAssignments.SelectedValue);

        string AssignmentName = txtEditGeneralQuizAssignmentName.Text;
        string AssignmentDirections = txtEditGeneralQuizAssignmentDirections.Value;

        int MaximumAttempts = Convert.ToInt32(ddlistEditQuizGeneralNumberOfAttempts.SelectedValue);
        int NumberOfQuestions = Convert.ToInt32(ddlistEditQuizGeneralNumberOfQuestionsToGenerate.SelectedValue);

        DateTime StartDateTime = Convert.ToDateTime(txtEditQuizGeneralStartDate.Text + " " + txtEditQuizGeneralStartDateTime.Text);
        DateTime EndDateTime = Convert.ToDateTime(txtEditQuizGeneralEndDate.Text + " " + txtEditQuizGeneralEndDateTime.Text);

        int EndDateTimeHours = Convert.ToInt32(txtEditQuizGeneralSendNotificationEmailQuizEndHours.Text);

        bool SendNotify = chkboxEditQuizGeneralSendNotificationEmail.Checked;
        bool SendNotifyStart = false;
        bool SendNotifyEnd = false;
        bool SendResult = chkboxEditQuizGeneralSendQuizResult.Checked;

        XDocument xDocQuizAssignment = new XDocument();
        if (strQuizAssignment != String.Empty)
            xDocQuizAssignment = XDocument.Parse(strQuizAssignment);

        if (SendNotify)
        {
            SendNotifyStart = chkboxEditQuizGeneralSendNotificationEmailQuizStart.Checked;
            SendNotifyEnd = chkboxEditQuizGeneralSendNotificationEmailQuizEnd.Checked;
        }

        if (chkboxEditQuizManualMode.Checked)
        {
            XDocument xDocManual = new XDocument();

            try
            {
                xDocManual = XDocument.Parse(txtEditQuizManualMode.Text);
            }
            catch
            {
                ModalPopupMessage.ShowModalPopup("ILE Message", "XML String entered in Manual Mode is not in a valid XML format.", 2);
                return;
            }

            xDocQuizAssignment = xDocManual;
        }

        bool result_1 = assignmentsLogic.UpdateAssignmentQuiz(xDocQuizAssignment.ToString(), MaximumAttempts, NumberOfQuestions, AssignmentID);
        bool result_2 = assignmentsLogic.UpdateAssignment("Quiz", AssignmentName, AssignmentDirections, SendNotifyStart, SendNotifyEnd, EndDateTimeHours, SendResult, StartDateTime, EndDateTime, AssignmentID);

        // Back up original relations before delete relations
        Assignments.RelationsDataTable originalRelations = assignmentsLogic.GetRelationsByAssignmentID(AssignmentID);
        bool result_3 = assignmentsLogic.DeleteRelationsByAssignmentID(AssignmentID);

        if (result_3)
        {
            foreach (ListItem item in lstboxEditSections.Items)
            {
                if (item.Selected)
                {
                    bool result_4 = assignmentsLogic.InsertRelation(AssignmentID, CourseID, Convert.ToInt32(item.Value), StandardID);

                    // When new inserting of relations fail,
                    if (!result_4)
                    {
                        // Delete all inserted relatinos.
                        bool tempResult = assignmentsLogic.DeleteRelationsByAssignmentID(AssignmentID);
                        if (tempResult)
                        {
                            // Undo Delete Relations
                            foreach (Assignments.RelationsRow relation in originalRelations)
                            {
                                assignmentsLogic.InsertRelation(relation.AssignmentID, relation.CourseID, relation.SectionNumber, relation.StandardID);
                            }
                        }
                        result_3 = false;
                        break;
                    }
                }
            }
        }
        else
        {
            ileGlobal.RecordError("Admin/Assignments_Quiz.aspx.cs:WizardEditQuizAssignment_FinishButtonClick:001", "Failed to delete relations.", 1, Request.Browser);
        }

        if (result_1 && result_2 && result_3)
        {
            // *SteveMsg
            string _message = "Successfully Updated the Quiz Assignment.";
            ModalPopupMessage.ShowModalPopup_Redirect("ILE Message", _message, 1, "Assignments_Quiz.aspx");
        }
        else
        {
            // *SteveMsg
            string _message = "Failed to Update the Quiz Assignment.";
            ModalPopupMessage.ShowModalPopup("ILE Message", _message, 2);
            ileGlobal.RecordError("Admin/Assignments_Quiz.aspx.cs:WizardEditQuizAssignment_FinishButtonClick:000", "Failed to update Quiz Assignmemnt", 1, Request.Browser);
        }

        strQuizAssignment = xDocQuizAssignment.ToString();
    }

    protected void chkboxEditQuizManualMode_CheckedChanged(object sender, EventArgs e)
    {
        CheckBox Sender = ((CheckBox)sender);

        if (Sender.Checked)
        {
            PanelEditQuizManualMode.Visible = true;
        }
        else
        {
            PanelEditQuizManualMode.Visible = false;
        }

    }

    protected void btnQuizDelete_Click(object sender, EventArgs e)
    {
        AssignmentsBLL assignmentLogic = new AssignmentsBLL();
        int AssignmentID = Convert.ToInt32(GridViewAssignments.SelectedValue);
        bool result = assignmentLogic.DeleteAssignment(AssignmentID);

        if (result)
        {
            // *SteveMsg
            string _message = "The quiz qssignment has been successfully deleted.";
            ModalPopupMessage.ShowModalPopup_Redirect("ILE Message", _message, 1, "Assignments_Quiz.aspx");
        }
        else
        {
            // *SteveMsg
            string _message = "Failed to delete the quiz assignment.";
            ModalPopupMessage.ShowModalPopup("ILE Message", _message, 2);
        }
    }

    #endregion


    #endregion

    protected void GridViewAssignments_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            GridView grdview = (GridView)sender;
            grdview.Sort("AssignmentTitle", SortDirection.Ascending);
        }
    }

    protected void txtSections_TextChanged(object sender, EventArgs e)
    {
        ConvertTextToSelectedListItem(((TextBox)sender).Text, lstboxSections);
    }

    protected void txtEditSections_TextChanged(object sender, EventArgs e)
    {
        ConvertTextToSelectedListItem(((TextBox)sender).Text, lstboxEditSections);
    }

    protected void ConvertTextToSelectedListItem(string text, ListBox listbox)
    {
        string original = text;
        string formatted = String.Empty;
        bool isContinuous = false;
        int[] sections = new int[60];
        int i = 0, j = 0, k = 0;

        listbox.SelectedIndex = -1;

        foreach (char ch in original)
        {
            if (ch >= '0' && ch <= '9')
            {
                formatted += ch;
            }
            else if (ch == ',')
            {
                try
                {
                    sections[i++] = Convert.ToInt32(formatted);
                }
                catch
                {
                    ModalPopupMessage.ShowModalPopup("ILE Message", "Text is not in format.", 2);
                    break;
                }

                if (isContinuous)
                {
                    k = i;
                    for (j = sections[i - 2] + 1; j < sections[i - 1]; j++)
                    {
                        sections[k++] = j;
                    }
                    i = k;
                    isContinuous = false;
                }

                formatted = String.Empty;
            }
            else if (ch == '-')
            {
                try
                {
                    sections[i++] = Convert.ToInt32(formatted);
                }
                catch
                {
                    ModalPopupMessage.ShowModalPopup("ILE Message", "Text is not in format.", 2);
                    break;
                }
                isContinuous = true;
                formatted = String.Empty;
            }
            else if (ch == ' ')
            {

            }
            else
            {
                ModalPopupMessage.ShowModalPopup("ILE Message", "Only numbers, ',', and '-' are allowed.", 2);
                break;
            }
        }

        try
        {
            sections[i++] = Convert.ToInt32(formatted);

            if (isContinuous)
            {
                k = i;
                for (j = sections[i - 2] + 1; j < sections[i - 1]; j++)
                {
                    sections[k++] = j;
                }
                isContinuous = false;
            }
        }
        catch
        {
        }

        foreach (int section in sections)
        {
            if (section == 0)
                break;

            ListItem item = new ListItem();
            try
            {
                item = listbox.Items.FindByValue(section.ToString());
                if (item.Selected)
                    ModalPopupMessage.ShowModalPopup("ILE Message", "Warning: Duplicate Sections.", 0);
                else
                    item.Selected = true;
            }
            catch
            {
                ModalPopupMessage.ShowModalPopup("ILE Message", "You have entered section number that does not exist. Sect." + section.ToString(), 2);
                break;
            }
        }
    }
}
